<template>
	<view @click="handleRefresh" class="service-icon" :style="{ left: posX + 'px', top: posY + 'px' }"
		@touchstart="startDrag" @touchmove.stop.prevent="dragging" @touchend="endDrag">
		<image class="refresh" :src="icon" />
		<view class="font-26 mar-top-10">客服</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'

	import {
		postMultiGet
	} from '@/api/currency.js'
	import util from '@/util/util';

	const emit = defineEmits(['refresh'])
	const isValidTime = ref(false)
	const handleRefresh = () => {
		const currentHour = new Date().getHours(); // 获取当前小时
		// 判断是否在 8 点到 22 点之间
		const isValidTime = ref().value = (currentHour >= 8 && currentHour < 22);

		if (isValidTime) {
			postMultiGet({
				codes: ['service_tel']
			}).then(res => {
				uni.makePhoneCall({
					phoneNumber: res.data.lists.service_tel, // 电话号码
					success: function() {
						console.log('Call successful');
					},
					fail: function(err) {
						console.error('Call failed: ', err);
					}
				});
			})
		} else {
			uni.$u.toast('客服在线时间为：8:00~22:00');
		}
	}

	const posX = ref(0)
	const posY = ref(0)
	let startX = 0
	let startY = 0
	let screenWidth = 0
	let screenHeight = 0

	let safeAreaInsetsBottom = 0
	util.getClient().then(res => {
		if (res == 'wx_mini') {
			safeAreaInsetsBottom = 30;
		}
	})
	const iconSize = 60 // 图标的大小

	const props = defineProps({
		icon: {
			type: String,
			default: '/static/icons/refresh.png'
		}
	})

	onMounted(() => {
		const systemInfo = uni.getSystemInfoSync()
		screenWidth = systemInfo.screenWidth
		screenHeight = systemInfo.windowHeight

		// 初始化位置
		posX.value = screenWidth - 15 - 60 // 60是图标的宽度
		posY.value = screenHeight - safeAreaInsetsBottom - 30 - iconSize // 60是图标的高度
	})

	const startDrag = (event) => {
		startX = event.touches[0].clientX - posX.value
		startY = event.touches[0].clientY - posY.value
	}

	const dragging = (event) => {
		let newX = event.touches[0].clientX - startX
		let newY = event.touches[0].clientY - startY

		newX = Math.max(0, Math.min(newX, screenWidth - iconSize))
		newY = Math.max(0, Math.min(newY, screenHeight - safeAreaInsetsBottom - iconSize))

		posX.value = newX
		posY.value = newY
	}

	const endDrag = () => {}
</script>

<style scoped>
	.service-icon {
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		width: 120rpx;
		height: 120rpx;
		background-color: #FFFFFF;
		box-shadow: 0 6rpx 15rpx 1rpx rgba(123, 123, 123, 0.33);
		position: fixed;
		z-index: 98;
		border-radius: 50%;
	}

	.refresh {
		width: 57rpx;
		height: 58.3rpx;
	}
</style>